package com.zjsru.gateway.filter;

import com.zjsru.gateway.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class TokenAuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求
        ServerHttpRequest exchangeRequest = exchange.getRequest();
        String path = exchangeRequest.getPath().toString();
        //2.如果路径中包含白名单就放行
        if (path.contains("/user/public")){
            return chain.filter(exchange);
        }
        //3.获取token
        String res = exchangeRequest.getHeaders().getFirst("Authorization");
        if(res == null || !res.startsWith("Bearer ")){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        String token = res.substring(7);
        //5.解析token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = claims.get("user_id", Integer.class);
            log.info("用户id:{}", userId);
        } catch (Exception e) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //6.放行
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
